package cn.yuemouren.security.app.validate.code;

import cn.yuemouren.security.core.validate.code.ValidateCode;
import cn.yuemouren.security.core.validate.code.ValidateCodeException;
import cn.yuemouren.security.core.validate.code.ValidateCodeRepository;
import cn.yuemouren.security.core.validate.code.ValidateCodeType;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.concurrent.TimeUnit;

/**
 * @Author: Timi
 * @Description: 验证码入Redis操作类
 * @Date: 2020/7/2 21:25
 * @Version: v1.0
 */
@Component
public class RedisValidateCodeRepository implements ValidateCodeRepository {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType type) {
        redisTemplate.opsForValue().set(buildRedisKey(request,type),code,30, TimeUnit.MINUTES);
    }

    @Override
    public ValidateCode get(ServletWebRequest request, ValidateCodeType type) {
        Object result = redisTemplate.opsForValue().get(buildRedisKey(request, type));
        if(null == result){
            return null;
        }
        return (ValidateCode)result;
    }

    @Override
    public void remove(ServletWebRequest request, ValidateCodeType type) {
        redisTemplate.delete(buildRedisKey(request,type));
    }

    private String buildRedisKey(ServletWebRequest request,ValidateCodeType type){
        String deviceId = request.getHeader("deviceId");
        if (StringUtils.isBlank(deviceId)) {
            throw new ValidateCodeException("请在请求头中携带deviceId参数");
        }
        return "REDIS_CODE_"+type.toString().toUpperCase()+"_"+deviceId;
    }
}
